<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="学生姓名" prop="studentName">
        <el-input v-model="queryParams.studentName" placeholder="请输入学生姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="学生年龄" prop="studentAge">
        <el-input v-model="queryParams.studentAge" placeholder="请输入学生年龄" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="民族" prop="nation">
        <el-input v-model="queryParams.nation" placeholder="请输入民族" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="联系方式" prop="studentPhone">
        <el-input v-model="queryParams.studentPhone" placeholder="请输入联系方式" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="年级" prop="studentBelongToGrade">
        <el-select v-model="queryParams.studentBelongToGrade" placeholder="请选择年级" style="width:100%" clearable @change="queryParams.studentBelongToClass=null">
          <el-option v-for="dict in gradesList" :key="dict.gid" :label="dict.gradeName" :value="dict.gid"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="班级" prop="studentBelongToClass">
        <el-select v-model="queryParams.studentBelongToClass" placeholder="请选择年级" style="width:100%" clearable>
          <el-option v-for="dict in classesList.filter(item => item.gid === queryParams.studentBelongToGrade)" :key="dict.cid" :label="dict.className" :value="dict.cid"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:student:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['system:student:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:student:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['system:student:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['system:student:import']">
        <el-upload multiple :action="uploadFileUrl" accept=".xlsx" :on-success="handleImport" :show-file-list="false" :headers="headers">
          <el-button type="warning" plain icon="el-icon-upload" size="mini">批量导入</el-button>
        </el-upload>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['system:student:download']">
        <el-button type="success" plain icon="el-icon-download" size="mini" @click="handleDownload">模板下载</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="studentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" prop="studentName" width="80" />
      <el-table-column label="性别" align="center" prop="studentSex" width="50" />
      <el-table-column label="年龄" align="center" prop="studentAge" width="50" />
      <el-table-column label="出生年月" align="center" prop="dateOfBirth" width="100" />
      <el-table-column label="民族" align="center" prop="nation" width="60" />
      <el-table-column label="身份证号" align="center" prop="cardNumber" width="160" />
      <el-table-column label="学籍" align="center" prop="studentStatus" width="80" />
      <el-table-column label="住址" align="center" prop="studentAddress" />
      <el-table-column label="联系方式" align="center" prop="studentPhone" width="120" />
      <el-table-column label="年级" align="center" prop="studentBelongToGrade" width="100">
        <template slot-scope="scope">
          {{selectDictLabel(gradesList,scope.row.studentBelongToGrade,"gid","gradeName")}}
        </template>
      </el-table-column>
      <el-table-column label="班级" align="center" prop="studentBelongToClass" width="60">
        <template slot-scope="scope">
          {{selectDictLabel(classesList,scope.row.studentBelongToClass,"cid","className")}}
        </template>
      </el-table-column>
      <el-table-column label="分科" align="center" prop="teacherSex" width="60">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.student_division" :value="scope.row.division" />
        </template>
      </el-table-column>
      <el-table-column label="分数" align="center" prop="fraction" width="60" />
      <el-table-column label="状态" align="center" prop="status" width="60">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.student_status" :value="scope.row.division"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:student:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:student:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改学生对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="学生姓名" prop="studentName">
          <el-input v-model="form.studentName" placeholder="请输入学生姓名" />
        </el-form-item>
        <el-form-item label="学生年龄" prop="studentAge">
          <el-input v-model="form.studentAge" placeholder="请输入学生年龄" />
        </el-form-item>
        <el-form-item label="出生年月" prop="dateOfBirth">
          <el-input v-model="form.dateOfBirth" placeholder="请输入出生年月" />
        </el-form-item>
        <el-form-item label="民族" prop="nation">
          <el-input v-model="form.nation" placeholder="请输入民族" />
        </el-form-item>
        <el-form-item label="身份证号" prop="cardNumber">
          <el-input v-model="form.cardNumber" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="住址" prop="studentAddress">
          <el-input v-model="form.studentAddress" placeholder="请输入住址" />
        </el-form-item>
        <el-form-item label="联系方式" prop="studentPhone">
          <el-input v-model="form.studentPhone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="年级" prop="studentBelongToGrade">
          <el-select v-model="form.studentBelongToGrade" placeholder="请选择年级" style="width:100%" @change="form.studentBelongToClass=null">
            <el-option v-for="dict in gradesList" :key="dict.gid" :label="dict.gradeName" :value="dict.gid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="studentBelongToClass">
          <el-select v-model="form.studentBelongToClass" placeholder="请选择年级" style="width:100%">
            <el-option v-for="dict in classOption" :key="dict.cid" :label="dict.className" :value="dict.cid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分科" prop="division">
          <el-select v-model="form.division" placeholder="请选择分科" style="width:100%">
            <el-option v-for="dict in dict.type.student_division" :key="dict.value" :label="dict.label" :value="Number(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分数" prop="fraction">
          <el-input-number style="width:100%" :precision="1" :step="0.5" v-model="form.fraction" :min="1" :max="999" label="分数"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStudent, getStudent, delStudent, addStudent, updateStudent } from "@/api/system/student";
import { listGrades } from "@/api/system/grades";
import { listClasses } from "@/api/system/classes";
import axios from 'axios'
import { getToken } from "@/utils/auth";
export default {
  name: "Student",
  dicts: ["student_status", "student_division"],
  computed: {
    classOption() {
      return this.classesList.filter(item => item.gid === this.form.studentBelongToGrade)
    }
  },
  data() {
    return {
      gradesList: [],
      classesList: [],
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/system/student/uploadAndUpdate", // 批量导入地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学生表格数据
      studentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sid: null,
        studentName: null,
        studentSex: null,
        studentAge: null,
        dateOfBirth: null,
        nation: null,
        cardNumber: null,
        studentStatus: null,
        studentAddress: null,
        studentPhone: null,
        studentBelongToGrade: null,
        studentBelongToClass: null,
        division: null,
        fraction: null,
        status: null,
        isDelete: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getGradesList()
    this.getClassesList()
  },
  methods: {
    /** 批量导入 */
    handleImport(res, file) {
      if (res.code === 200) {
        this.getList()
        this.$message.success("导入成功！")
      } else {
        this.$message.error(res.msg)
      }
    },
    /** 批量导入失败 */
    handleUploadError(err) {
      this.$modal.msgError("批量导入失败，请重试");
    },
    /** 模板下载 */
    async handleDownload() {
      try {
        const response = await axios.get('/学生模板.xlsx', { responseType: 'blob', });
        const blob = new Blob([response.data], { type: response.headers['content-type'] });
        const downloadLink = document.createElement('a');
        downloadLink.href = window.URL.createObjectURL(blob);
        downloadLink.download = '学生模板.xlsx';
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
      } catch (error) {
        this.$message.error("模板下载失败，请联系管理员！")
      }
    },
    /** 查询学生列表 */
    getList() {
      this.loading = true;
      listStudent(this.queryParams).then(response => {
        this.studentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询年级列表 */
    getGradesList() {
      listGrades({ pageNum: 1, pageSize: 1000 }).then(response => {
        this.gradesList = response.rows;
      });
    },
    /** 查询班级列表 */
    getClassesList() {
      listClasses({ pageNum: 1, pageSize: 1000 }).then(response => {
        this.classesList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        studentId: null,
        sid: null,
        studentName: null,
        studentSex: null,
        studentAge: null,
        dateOfBirth: null,
        nation: null,
        cardNumber: null,
        studentStatus: null,
        studentAddress: null,
        studentPhone: null,
        studentBelongToGrade: null,
        studentBelongToClass: null,
        division: null,
        fraction: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDelete: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.studentId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学生";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const studentId = row.studentId || this.ids
      getStudent(studentId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改学生信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.studentId != null) {
            updateStudent(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStudent(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const studentIds = row.studentId || this.ids;
      this.$modal.confirm('是否确认删除学生编号为"' + studentIds + '"的数据项？').then(function () {
        return delStudent(studentIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/student/export', {
        ...this.queryParams
      }, `student_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
